import { useState } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { getStoreByPhone } from '../services/pocketBaseService';

function StoreSelectModal({ stores, onSelect, onClose }) {
  return (
    <div className="fixed inset-0 bg-black bg-opacity-30 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-lg p-6 w-full max-w-lg">
        <h3 className="text-lg font-bold mb-4">请选择店铺</h3>
        <ul className="space-y-4 max-h-80 overflow-y-auto">
          {stores.map((store) => (
            <li key={store.id} className="border rounded p-3 hover:bg-gray-100 cursor-pointer" onClick={() => onSelect(store)}>
              <div className="font-semibold">{store.store_name}</div>
              <div className="text-sm text-gray-600">地址：{store.store_address}</div>
              <div className="text-sm text-gray-600">营业时间：{store.business_time}</div>
              <div className="text-sm text-gray-600">手机号：{store.own_phone}</div>
            </li>
          ))}
        </ul>
        <button className="mt-6 w-full py-2 bg-gray-300 rounded hover:bg-gray-400" onClick={onClose}>取消</button>
      </div>
    </div>
  );
}

function LoginPage() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [phone, setPhone] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [storeModalOpen, setStoreModalOpen] = useState(false);
  const [storeOptions, setStoreOptions] = useState([]);
  const [selectedStore, setSelectedStore] = useState(null);
  const { login } = useAuth();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    if (!email || !password || !phone) {
      setError('请填写邮箱、密码和手机号');
      setLoading(false);
      return;
    }

    try {
      // 先查找店铺
      const storeRes = await getStoreByPhone(phone);
      if (!storeRes.success) {
        setError(storeRes.error || '手机号查询店铺失败');
        setLoading(false);
        return;
      }
      // 适配新数据结构，直接取items数组
      const stores = Array.isArray(storeRes.data?.items) ? storeRes.data.items : [];
      if (stores.length === 0) {
        setError('未找到对应店铺');
        setLoading(false);
        return;
      } else if (stores.length === 1) {
        // 只有一个店铺，直接登录
        setSelectedStore(stores[0]);
        await doLogin(stores[0].id);
      } else {
        // 多个店铺，弹窗选择
        setStoreOptions(stores);
        setStoreModalOpen(true);
        setLoading(false);
      }
    } catch (err) {
      setError('查询店铺时发生错误，请稍后再试');
      setLoading(false);
    }
  };

  const doLogin = async (storeId) => {
    setLoading(true);
    setError('');
    try {
      const result = await login(email, password, phone, storeId);
      if (!result.success) {
        setError(result.error || '登录失败，请检查邮箱、密码和手机号');
      }
    } catch (err) {
      setError('登录时发生错误，请稍后再试');
      console.error('登录错误:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleStoreSelect = (store) => {
    setStoreModalOpen(false);
    setSelectedStore(store);
    doLogin(store.id);
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8">
        <div>
          <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
            商户版核销码管理系统
          </h2>
          <p className="mt-2 text-center text-sm text-gray-600">
            请登录以继续
          </p>
        </div>
        <form className="mt-8 space-y-6" onSubmit={handleSubmit}>
          <div className="rounded-md shadow-sm -space-y-px">
            <div>
              <label htmlFor="email-address" className="sr-only">
                邮箱地址
              </label>
              <input
                id="email-address"
                name="email"
                type="email"
                autoComplete="email"
                required
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
                placeholder="邮箱地址"
              />
            </div>
            <div>
              <label htmlFor="password" className="sr-only">
                密码
              </label>
              <input
                id="password"
                name="password"
                type="password"
                autoComplete="current-password"
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
                placeholder="密码"
              />
            </div>
            <div>
              <label htmlFor="phone" className="sr-only">
                店铺主人手机号
              </label>
              <input
                id="phone"
                name="phone"
                type="text"
                autoComplete="tel"
                required
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
                placeholder="店铺主人手机号"
              />
            </div>
          </div>

          {error && (
            <div className="text-sm text-red-600 text-center">
              {error}
            </div>
          )}

          <div>
            <button
              type="submit"
              disabled={loading}
              className={`group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white ${
                loading ? 'bg-indigo-400' : 'bg-indigo-600 hover:bg-indigo-700'
              } focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500`}
            >
              {loading ? '登录中...' : '登录'}
            </button>
          </div>
        </form>
      </div>
      {storeModalOpen && (
        <StoreSelectModal
          stores={storeOptions}
          onSelect={handleStoreSelect}
          onClose={() => setStoreModalOpen(false)}
        />
      )}
    </div>
  );
}

export default LoginPage;